/*
 * Copyright 2016-2019 yoara
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package yhao.infra.web.common.tcc;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Tcc请求的上下文Holder
 *
 * @author yoara
 */
public class TccCommandHolder {
    private final static ThreadLocal<Map<String, Object>> tccContextHolder = new ThreadLocal<>();
    private final static String TCC_ENABLED = "TCC_ENABLED";
    private final static String TCC_ACTION_LIST = "TCC_ACTION_LIST";

    public static boolean tccEnabled(){
        return getHolder().containsKey(TCC_ENABLED);
    }

    public static void enableTcc(){
        getHolder().put(TCC_ENABLED,true);
        getHolder().put(TCC_ACTION_LIST,new ArrayList<TccCommandAction>());
    }

    public static void removeTcc(){
        getHolder().remove(TCC_ENABLED);
        ((List)getHolder().get(TCC_ACTION_LIST)).clear();
        getHolder().remove(TCC_ACTION_LIST);
    }

    public static boolean addTccCommandAction(TccCommandAction action){
        if(!tccEnabled()){
            return false;
        }
        return ((List)getHolder().get(TCC_ACTION_LIST)).add(action);
    }

    public static List<TccCommandAction> getTccCommandActionList(){
        if(!tccEnabled()){
            return null;
        }
        return ((List)getHolder().get(TCC_ACTION_LIST));
    }

    public static List<String> doTccCommandFallback(){
        List<String> msgList = new ArrayList<>();
        if(tccEnabled()){
            List<TccCommandAction> actionList = getTccCommandActionList();
            for(TccCommandAction action:actionList){
                try {
                    action.getFallback().doFallback();
                    msgList.add("");
                } catch (Exception e) {
                    msgList.add(e.getMessage());
                }
            }
        }
        return msgList;
    }

    private static Map<String, Object> getHolder(){
        Map<String, Object> holder = tccContextHolder.get();
        if(holder == null) {
            holder = new HashMap<>();
            tccContextHolder.set(holder);
        }
        return holder;
    }

    public static <T> T doInContext(TccCommandContextAction<T> action){
        enableTcc();
        try{
            return action.dealTarget();
        }catch (Throwable e){
            return action.dealFallback(e);
        } finally{
            removeTcc();
        }
    }
}
